<?php
declare (strict_types=1);

namespace app\listener\user;

use app\services\user\UserTokenServices;
use crmeb\interfaces\ListenerInterface;

class UserToken implements ListenerInterface
{
    /**
     * 登录完成 后置事件
     * @param $event
     * @return void
     */
    public function handle($event): void
    {
        [$user_id, $token, $device_type] = $event;

        /** @var UserTokenServices $userTokenServices */
        $userTokenServices = app()->make(UserTokenServices::class);

        $where = [];
        $where[] = ['user_id', '=', $user_id];
        $where[] = ['device_type', '=', $device_type];
        /** @var UserTokenServices $findUserToken */
        $findUserToken = $userTokenServices->getOne($where);

        $currentTime = time();
        $expireTime = $currentTime + 24 * 3600 * 180;

        if (empty($findUserToken)) {
            $arr = [];
            $arr['token'] = $token;
            $arr['expire_time'] = $expireTime;
            $arr['create_time'] = $currentTime;
            $arr['device_type'] = $device_type;
            $arr['user_id'] = $user_id;
            $userTokenServices->save($arr);
        } else {
            $userTokenServices->update($findUserToken->id,[
                'token' => $token,
                'expire_time' => $expireTime,
                'create_time' => $currentTime
            ]);
        }
    }
}
